<?php

/**
 * 用户模型
 */

namespace app\api\model;


use app\api\controller\Bind;
use app\api\controller\Config;
use app\common\lib\RedisKey;
use app\common\lib\RespCode;
use app\common\model\BaseModel;
use custom\Err;
use custom\Log;
use custom\Token;
use PDOStatement;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\Model;

class User extends BaseModel {

    /**
     * 获取用户详情
     * @param $uid
     * @param string $field
     * @return array|PDOStatement|string|Model|null
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getInfo($uid, $field = '*') {
        return Db::name('user')->where(['id' => $uid])->field($field)->find();
    }

    /**
     * 个人信息
     * @param $params
     * @return array
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getpersonal($params) {
        $data = Db::name('user')->field('cover,nickname,phone,is_push')->find($params['user_id']);
        if (empty($data['phone'])) {
            $phone = '';
        } else {
            $phone = $data['phone'];
        }
        $main_id = md5(md5($params['user_id']));
        if (empty(UserDemand::getMycount($params['user_id']))) {
            $is_demand = 0;
        } else {
            $is_demand = 1;
        }
        return ['avatar' => empty($data['cover']) ? config('global.default_avt') : $data['cover'], 'nickname' => base64_decode($data['nickname']), 'phone' => $phone, 'id' => $main_id, 'is_demand' => $is_demand, 'is_push' => $data['is_push']];
    }

    /**
     * 修改昵称
     * @param $params
     * @return int|string
     * @throws Exception
     * @throws PDOException
     */
    public static function editNickname($params) {
        $data = [
            'nickname' => base64_encode($params['nickname'])
        ];
        return Db::name('user')->where('id', $params['user_id'])->update($data);
    }

    /**
     * 修改电话
     * @param $new_phone
     * @param $id
     * @return int|string
     * @throws Exception
     * @throws PDOException
     */
    public static function editMobile($new_phone, $id) {
        if (db("user")->where('phone', $new_phone)->select()) {
            return false;
        }
        return Db::name("user")->where('id', $id)->update(['phone' => $new_phone]);
    }

    /**
     * 用户注销
     * @param $params
     * @return bool
     */
    public static function del_user($params, $headers) {
        Db::transaction(function () use ($params, $headers) {
            $userinfo = Db::name("user")->find($params['user_id']);
            $data = [
                'id' => $userinfo['id'],
                'phone' => $userinfo['phone'],
                'openid' => $userinfo['openid'],
                'ios_openid' => $userinfo['ios_openid'],
                'android_openid' => $userinfo['android_openid'],
                'gzh_openid' => $userinfo['gzh_openid'],
                'apple_id' => $userinfo['apple_id'],
                'source' => $userinfo['source'],
                'nickname' => $userinfo['nickname'],
                'cover' => $userinfo['cover'],
                'pwd' => $userinfo['pwd'],
                'os' => $userinfo['os'],
                'version' => $userinfo['version'],
                'registration_id' => $userinfo['registration_id'],
                'itime' => time(),
            ];
            Db::name('user_del')->insert($data);
            Db::name('user')->delete($params['user_id']);
            $Token = new  Token();
            $Token->delUserToken($headers['token'], $Token::API_TOKEN);
        });
    }

    /**
     * 修改头像
     * @param $params
     * @return int|string
     * @throws Exception
     * @throws PDOException
     */
    public static function editAvatar($params) {
        $data = [
            'cover' => $params['avatar']
        ];
        return Db::name('user')->where('id', $params['user_id'])->update($data);
    }

    /**
     * 根据openid查找用户号
     * @param $openid
     * @return array|PDOStatement|string|Model|null
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function get_openid($openid) {
        return Db::name("user")->where("openid", $openid)->find();
    }

    /**
     * 微信登录
     * @param $openid
     * @param $headr
     * @return array
     * @throws Exception
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function wxLogin($openid, $headers, $type) {
        if ($type == 1) {//小程序
            $opend_type = 'openid';
        }
        if ($type == 2) {//ios
            $opend_type = 'ios_openid';
        }
        if ($type == 3) {//android
            $opend_type = 'android_openid';
        }
        $data = Db::name('user')
            ->where($opend_type, $openid)
            ->find();
        self::clearRegistrationid($headers['registrationid']);
        Db::name("user")
            ->where($opend_type, $openid)
            ->update(['registration_id' => $headers['registrationid']]);
        $uid = $data['id'];
        $avatar = empty($data['cover']) ? config('global.default_avt') : $data['cover'];
        $account = $data['phone'];
        $Token = new Token();
        $token_ = $Token->getToken($uid, $headers, $Token::API_TOKEN, $Token::EXPIRE_TIME, RedisKey::APP_TOKEN_HASH);
        $main_id = md5(md5($data['id']));
        if (empty(UserDemand::getMycount($uid))) {
            $is_demand = 0;
        } else {
            $is_demand = 1;
        }
        return ['token' => $token_, 'msg' => '登录成功', 'type' => 1, 'avatar' => $avatar, 'account' => $account, 'id' => $main_id, 'is_push' => $data['is_push'], 'is_demand' => $is_demand];
    }

    /**
     * 通过三方账户创建
     * @param $userinfo
     * @param $headers
     * @param $source
     * @return array
     * @throws Exception
     */
    public static function createUser($userinfo, $headers, $source) {
        $is = Db::name('user')->where('phone', $userinfo['phone'])->find();
        self::clearRegistrationid($headers['registrationid']);
        $data = [
            'phone' => $userinfo['phone'],
            'openid' => $userinfo['openid'],
            'unionid' => $userinfo['unionid'],
            'ios_openid' => $userinfo['ios_openid'],
            'android_openid' => $userinfo['android_openid'],
            'gzh_openid' => $userinfo['gzh_openid'],
            'apple_id' => $userinfo['apple_id'],
            'source' => $source,
            'nickname' => $userinfo['nickname'],
            'cover' => $userinfo['headimgurl'],
            'pwd' => md5(123456),
            'os' => $headers['os'],
            'version' => $headers['version'],
            'registration_id' => $headers['registrationid'],
            'itime' => time(),
        ];
        if (!empty($is)) {//直接绑定
            $msg = '';
            if ($source == Bind::TYPE2) {
                if ($headers['os'] == 1) {//ios
                    $openid_type = 'ios_openid';
                }
                if ($headers['os'] == 2) {//android
                    $openid_type = 'android_openid';
                }
                if (Db::name("user")
                    ->where('phone', $userinfo['phone'])
                    ->value($openid_type)) {
                    throw new Exception('该手机号已绑定微信');
                } else {
                    $msg = '微信绑定成功';
                    Db::name("user")->where('phone', $userinfo['phone'])->update([$openid_type => $userinfo[$openid_type]]);
                }
            }
            if ($source == Bind::TYPE4) {
                if (Db::name("user")->where('phone', $userinfo['phone'])->value('apple_id')) {
                    throw new Exception('该手机号已绑定苹果账户');
                } else {
                    $msg = 'apple绑定成功';
                    Db::name("user")->where('phone', $userinfo['phone'])->update(['apple_id' => $userinfo['apple_id']]);
                }
            }
            if ($source == Bind::TYPE3) {
                if (Db::name("user")
                    ->where('phone', $userinfo['phone'])
                    ->value('openid')) {
                    throw new Exception('该手机号已绑定微信');
                } else {
                    $msg = '微信绑定成功';
                    Db::name("user")
                        ->where('phone', $userinfo['phone'])
                        ->update(['openid' => $userinfo['openid']]);
                }
            }
            Db::name('user')
                ->where('phone', $userinfo['phone'])
                ->update(['registration_id' => $headers['registrationid']]);
            $account = $is['phone'];
            $Token = new Token();
            $token_ = $Token->getToken($is['id'], $headers, $Token::API_TOKEN, $Token::EXPIRE_TIME, RedisKey::APP_TOKEN_HASH);
            $mainid = md5(md5($is['id']));
            if (empty(UserDemand::getMycount($is['id']))) {
                $is_demand = 0;
            } else {
                $is_demand = 1;
            }
            return ['token' => $token_, 'msg' => $msg, 'type' => 1, 'avatar' => empty($is['cover']) ? config('global.default_avt') : $is['cover'], 'account' => $account, 'id' => $mainid, 'is_push' => $is['is_push'], 'is_demand' => $is_demand];
        } else {
            $msg = '创建成功';
            $uid = Db::name('user')->insertGetId($data);
            $avatar = $data['cover'];
            $account = $data['phone'];
            $Token = new Token();
            $token_ = $Token->getToken($uid, $headers, $Token::API_TOKEN, $Token::EXPIRE_TIME, RedisKey::APP_TOKEN_HASH);
            $mainid = md5(md5($uid));
            $is_demand = 0;
            return ['token' => $token_, 'msg' => $msg, 'type' => 1, 'avatar' => empty($avatar) ? config('global.default_avt') : $avatar, 'account' => $account, 'id' => $mainid, 'is_push' => 1, 'is_demand' => $is_demand];
        }
    }

    /**
     * 根据apple_id找用户
     * @param $apple_id
     * @return array|PDOStatement|string|Model|null
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function get_appleId($apple_id) {
        return Db::name('user')->where('apple_id', $apple_id)->find();
    }

    /**
     * 苹果登录
     * @param $apple_id
     * @return array
     * @throws Exception
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function appleLogin($apple_id, $headers) {
        $data = Db::name('user')->where('apple_id', $apple_id)->find();
        self::clearRegistrationid($headers['registrationid']);
        Db::name("user")
            ->where('apple_id', $apple_id)
            ->update(['registration_id' => $headers['registrationid']]);
        $uid = $data['id'];
        $avatar = empty($data['cover']) ? config('global.default_avt') : $data['cover'];
        $account = $data['phone'];
        $Token = new Token();
        $token_ = $Token->getToken($uid, $headers, $Token::API_TOKEN, $Token::EXPIRE_TIME, RedisKey::APP_TOKEN_HASH);
        $main_id = md5(md5($data['id']));
        if (empty(UserDemand::getMycount($uid))) {
            $is_demand = 0;
        } else {
            $is_demand = 1;
        }
        return ['token' => $token_, 'msg' => '登录成功', 'type' => 1, 'avatar' => $avatar, 'account' => $account, 'id' => $main_id, 'is_push' => $data['is_push'], 'is_demand' => $is_demand];
    }

    /**
     * 通过手机号检测用户
     * @param $params
     * @param $headers
     * @param $source
     * @return array
     * @throws Exception
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function checkUser2($params, $headers, $source) {
        $data = Db::name('user')->where('phone', $params['phone'])->find();
        self::clearRegistrationid($headers['registrationid']);
        if (empty($data)) {
            $insert = [
                'phone' => $params['phone'],
                'openid' => $params['openid'],
                'unionid' => $params['unionid'],
                'ios_openid' => $params['ios_openid'],
                'android_openid' => $params['android_openid'],
                'gzh_openid' => $params['gzh_openid'],
                'apple_id' => $params['apple_id'],
                'source' => $source,
                'nickname' => $params['nickname'],
                'cover' => $params['headimgurl'],
                'pwd' => md5(123456),
                'os' => $headers['os'],
                'version' => $headers['version'],
                'registration_id' => $headers['registrationid'],
                'itime' => time(),
            ];
            $uid = Db::name('user')->insertGetId($insert);
            $avatar = $params['headimgurl'];
            $account = $params['phone'];
            $is_push = 1;
            $msg = '创建成功';
        } else {
            Db::name("user")
                ->where('phone', $params['phone'])
                ->update(['registration_id' => $headers['registrationid']]);
            $uid = $data['id'];
            $avatar = $data['cover'];
            $account = $data['phone'];
            $is_push = $data['is_push'];
            $msg = '登录成功';
        }
        $Token = new Token();
        $token_ = $Token->getToken($uid, $headers, $Token::API_TOKEN, $Token::EXPIRE_TIME, RedisKey::APP_TOKEN_HASH);
        $mainid = md5(md5($uid));
        if (empty(UserDemand::getMycount($uid))) {
            $is_demand = 0;
        } else {
            $is_demand = 1;
        }
        return ['token' => $token_, 'msg' => $msg, 'type' => 1, 'avatar' => empty($avatar) ? config('global.default_avt') : $avatar, 'account' => $account, 'id' => $mainid, 'is_push' => $is_push, 'is_demand' => $is_demand];
    }

    /**
     * 绑定微信
     * @param $params
     * @param $openid
     * @return int|string
     * @throws Exception
     * @throws PDOException
     */
    public static function bindWx($params, $openid) {
        if (db('user')->where('id', $params['user_id'])->value('openid')) {
            throw new Exception('你的账号已绑定过微信');
        }
        if (self::get_openid($openid)) {
            throw new Exception('该微信已被绑定');
        }
        $re = Db::name('user')->where('id', $params['user_id'])->update(['openid' => $openid]);
        if (!$re) {
            throw new Exception('绑定失败');
        }
        return true;
    }

    /**
     * 修改推送状态
     * @param $params
     * @return int|string
     * @throws Exception
     * @throws PDOException
     */
    public static function editPushStatus($params) {
        if (empty($params['type'])) {
            $type = 0;
        } else {
            $type = 1;
        }
        return db('company_agent')->where('id', $params['agent_id'])->update(['is_push' => $type]);
    }

    /**
     * 清楚匹配$registrationid的用户
     * @param $registrationid
     * @throws Exception
     * @throws PDOException
     */
    public static function clearRegistrationid($registrationid) {
        Db::name("user")
            ->where('registration_id', $registrationid)
            ->update(['registration_id' => '']);
    }

}
